

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言以下介绍的都是常用的标准库 什么是标准库？ 就是python自带的工具包，不需要额外安装，只要安装了python，就可以在编程的时候直接拿来使用。 极大的提高了我们的开发效率。 而且由于是标准库，几乎不会存在 bug， 十分的稳定。 time我们开发程序时，时常要和时间打交道  校验当前时间 获取当前时间 获取时间戳，目的是为了获取当前时刻的唯一标识 计算程序运行时间  使用前需要 impor">
<meta property="og:type" content="article">
<meta property="og:title" content="python常用标准库">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2023/03/19/python/base/python%E5%B8%B8%E7%94%A8%E6%A0%87%E5%87%86%E5%BA%93/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言以下介绍的都是常用的标准库 什么是标准库？ 就是python自带的工具包，不需要额外安装，只要安装了python，就可以在编程的时候直接拿来使用。 极大的提高了我们的开发效率。 而且由于是标准库，几乎不会存在 bug， 十分的稳定。 time我们开发程序时，时常要和时间打交道  校验当前时间 获取当前时间 获取时间戳，目的是为了获取当前时刻的唯一标识 计算程序运行时间  使用前需要 impor">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-03-19T05:27:03.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.265Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="Python基础">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>python常用标准库 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="python常用标准库"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-03-19 13:27" pubdate>
          2023年3月19日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.2k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">python常用标准库</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>以下介绍的都是常用的标准库</p>
<p>什么是标准库？</p>
<p>就是python自带的工具包，不需要额外安装，只要安装了python，就可以在编程的时候直接拿来使用。</p>
<p>极大的提高了我们的开发效率。</p>
<p>而且由于是标准库，几乎不会存在 <strong>bug</strong>， 十分的稳定。</p>
<h1 id="time"><a href="#time" class="headerlink" title="time"></a>time</h1><p>我们开发程序时，时常要和时间打交道</p>
<ul>
<li>校验当前时间</li>
<li>获取当前时间</li>
<li>获取时间戳，目的是为了获取当前时刻的唯一标识</li>
<li>计算程序运行时间</li>
</ul>
<p>使用前需要 <code>import time</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> time<br><br>t = time.time()  <span class="hljs-comment"># 获取当前时间戳</span><br><br>time.sleep(<span class="hljs-number">5</span>)  <span class="hljs-comment"># 让程序睡眠一段时间，单位为s。这段代码就是让程序睡眠5秒</span><br><br>nowTime = time.strftime(<span class="hljs-string">&#x27;%Y-%m-%d %H:%M:%S&#x27;</span>)  <span class="hljs-comment"># 获取字符串格式的当前时间，示例: 2023-01-01 10:10:10</span><br><br>asctime = time.asctime()  <span class="hljs-comment"># 获取当前时间，不过是 国外的格式，示例：Sun Mar 19 13:29:03 2023</span><br><br>localtime = time.localtime(time.time())  <span class="hljs-comment"># 将时间戳转化成时间对象，时间对象会提供很多方法，比如获取年份、当前时间</span><br><br>mktime = time.mktime(localtime)  <span class="hljs-comment"># 将时间对象转化成时间戳</span><br><br>strptime = time.strptime(<span class="hljs-string">&quot;2000-08-06 22:29:35&quot;</span>,<span class="hljs-string">&#x27;%Y-%m-%d %H:%M:%S&#x27;</span>)  <span class="hljs-comment"># 将字符串类型的时间，转化成时间对象</span><br></code></pre></td></tr></table></figure>

<h1 id="os"><a href="#os" class="headerlink" title="os"></a>os</h1><p>os库，几乎全部都是 <strong>操作系统</strong> 的api，比如：</p>
<ul>
<li>获取路径</li>
<li>操作文件/文件夹</li>
</ul>
<p>使用前需要 <code>import os</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os<br><br>filePath = __file__  <span class="hljs-comment"># __file__ 是获取当前文件的路径，字符串格式的绝对路径</span><br><br>abspath = os.path.abspath(filePath)  <span class="hljs-comment"># 将字符串的路径转化成绝对路径</span><br><br>dirname = os.path.dirname(filePath)  <span class="hljs-comment"># 获取路径所在的文件夹路径</span><br><br>basename = os.path.basename(filePath)  <span class="hljs-comment"># 获取文件/文件夹本身的全名, 比如：test/test.py  获取出来就是test.py</span><br><br>joinpath = os.path.join(dirname, basename)  <span class="hljs-comment"># 将多个路径进行合成，不同路径之间会自动添加上路径分隔符, 支持 &#x27;../../../xxx&#x27;这种写法</span><br><br>listdir = os.listdir(dirname)  <span class="hljs-comment"># 获取路径下的所有文件/文件夹的名字，格式为列表。所以传入的参数必须为一个文件夹的路径，不然会报错</span><br><br>existspath = os.path.exists(filePath)  <span class="hljs-comment"># 判断路径对应的文件/文件夹是否还存在</span><br><br>isfile = os.path.isfile(filePath)  <span class="hljs-comment"># 判断路径对应的是否为一个文件</span><br><br>isdir = os.path.isdir(dirname)  <span class="hljs-comment"># 判断路径对应的是否为一个文件夹</span><br><br><span class="hljs-comment"># os.rename(dirname, &#x27;test1&#x27;)  # 将路径对应的文件/文件夹的名字进行修改</span><br><br><span class="hljs-comment"># os.remove(filePath)  # 删除路径指向的文件</span><br><br><span class="hljs-comment"># os.rmdir(dirname)  # 删除路径指向的文件夹, 只能删除空文件夹</span><br><br><span class="hljs-comment"># os.mkdir(dirname)  # 创建一个文件夹</span><br></code></pre></td></tr></table></figure>

<h1 id="random"><a href="#random" class="headerlink" title="random"></a>random</h1><p>获取随机数</p>
<p>使用前需要 <code>import random</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> random<br><br><span class="hljs-built_in">print</span>(random.randint(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>))  <span class="hljs-comment"># 随机生成1-10的整数</span><br><br><span class="hljs-built_in">print</span>(random.random())  <span class="hljs-comment"># 随机生成0-1之间的浮点数</span><br><br><span class="hljs-built_in">print</span>(random.randrange(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>))  <span class="hljs-comment"># 随机生成1-10的整数,包含1不包含10</span><br><br><span class="hljs-built_in">print</span>(random.choice([<span class="hljs-string">&#x27;1&#x27;</span>, <span class="hljs-string">&#x27;2&#x27;</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]))  <span class="hljs-comment"># 在可迭代对象随机抽取一个数据</span><br><br><span class="hljs-built_in">print</span>(random.sample([<span class="hljs-string">&#x27;1&#x27;</span>, <span class="hljs-string">&#x27;2&#x27;</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], <span class="hljs-number">2</span>))  <span class="hljs-comment"># 在可迭代对象随机抽取n个数据，返回一个列表</span><br><br><span class="hljs-built_in">print</span>(random.uniform(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>))  <span class="hljs-comment"># 获取[a,b)范围内的浮点数</span><br><br>li = [<span class="hljs-string">&#x27;1&#x27;</span>, <span class="hljs-string">&#x27;2&#x27;</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]<br><br>random.shuffle(li)  <span class="hljs-comment"># 把参数指定的数据中的元素打乱。参数必须是一个可变的数据类型。</span><br><span class="hljs-built_in">print</span>(li)  <span class="hljs-comment"># 打乱顺序</span><br></code></pre></td></tr></table></figure>

<h1 id="json"><a href="#json" class="headerlink" title="json"></a>json</h1><p>json转化工具包</p>
<p>可以将python中的数组、字典转化为字符串格式的json串</p>
<p>也可以将字符串格式的json串转化成数组、字典</p>
<p>使用前需要 <code>import json</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> json<br><br>data = &#123;<br>    <span class="hljs-string">&#x27;name&#x27;</span>: <span class="hljs-string">&#x27;muzhou&#x27;</span>,<br>    <span class="hljs-string">&#x27;age&#x27;</span>: <span class="hljs-string">&#x27;18&#x27;</span><br>&#125;<br><br>s = json.dumps(data)  <span class="hljs-comment"># 把dict转化成json字符串</span><br><span class="hljs-built_in">print</span>(s)<br><br>s = json.loads(s)  <span class="hljs-comment"># 把json字符串转化成dict</span><br><span class="hljs-built_in">print</span>(s)<br><br><span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;json.json&#x27;</span>, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>    json.dump(data, f)  <span class="hljs-comment"># 将json内容序列化到文档中</span><br><br><span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;json.json&#x27;</span>, <span class="hljs-string">&#x27;r&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>    read = json.load(f)  <span class="hljs-comment"># 读取json文件内容</span><br>    <span class="hljs-built_in">print</span>(read)<br></code></pre></td></tr></table></figure>


<h1 id="logging"><a href="#logging" class="headerlink" title="logging"></a>logging</h1><p>python中有<code>print</code>可以进行打印输出，那为什么我们还要学习logging</p>
<p>因为print语句，一旦创建后，执行到它时，就必须要运行。</p>
<p>但通常我们写程序的时候，是伴随着很多 <strong>调试</strong> 输出的，这个时候就需要有一个工具库来帮我们进行自动过滤调试日志。</p>
<p>并且，logging还有很好的 <strong>格式设置</strong>，以及很好的 <strong>输出日志文件、备份</strong> 的功能。</p>
<h2 id="logging-1"><a href="#logging-1" class="headerlink" title="logging"></a>logging</h2><p>常用有四个等级：</p>
<ul>
<li>debug</li>
<li>info</li>
<li>warning</li>
<li>error</li>
</ul>
<p>默认只会输出 <strong>warning</strong> 及以上的日志</p>
<p>我们可以通过 <code>logging.basicConfig(level=logging.DEBUG)</code> 来改写</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br>logging.basicConfig(level=logging.DEBUG)<br>logger = logging.getLogger(__name__)<br><br>logger.debug(<span class="hljs-string">&quot;This is debug log&quot;</span>)<br>logger.info(<span class="hljs-string">&quot;This is info log&quot;</span>)<br>logger.warning(<span class="hljs-string">&quot;This is warning log&quot;</span>)<br>logger.error(<span class="hljs-string">&quot;This is error log&quot;</span>)<br></code></pre></td></tr></table></figure>

<h2 id="调整日志输出端"><a href="#调整日志输出端" class="headerlink" title="调整日志输出端"></a>调整日志输出端</h2><p>前面介绍中，日志是直接打印在终端的，但真正的使用过程中往往要输出为日志文件，只需要配置basicConfig即可。</p>
<p>日志写入默认是追加写入，不会覆盖文件原有内容。</p>
<p>通过这种方式，控制台就不会输出日志了，日志都会默认存到文件中。</p>
<p>我们后面可以通过其他的方式来进行日志文件输出，并且可以打印到控制台中。</p>
<p>这里只是介绍一下，日志是可以直接输出到文件里面的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br><span class="hljs-comment"># 使用basicConfig调整日志输出至文件，filename=&#x27;demo01.log&#x27;</span><br>logging.basicConfig(filename=<span class="hljs-string">&#x27;demo01.log&#x27;</span>, level=logging.DEBUG)<br><span class="hljs-comment"># 清空后再写入filemode=&quot;w&quot;  一般不会这么用，都是采用默认的追加模式</span><br>logging.basicConfig(filename=<span class="hljs-string">&#x27;demo01.log&#x27;</span>, filemode=<span class="hljs-string">&quot;w&quot;</span>, level=logging.DEBUG)<br></code></pre></td></tr></table></figure>

<h2 id="调整日志格式"><a href="#调整日志格式" class="headerlink" title="调整日志格式"></a>调整日志格式</h2><p>我们可以发现，日志的输出十分单调。</p>
<p>而我们常常看到的日志一般会包含时间、日志类别、日志名称等其他信息。</p>
<p>这类信息是可以通过 <strong>调整</strong> 格式来进行改写的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br><span class="hljs-comment"># 输出日志打印时间，日志级别等</span><br>logging.basicConfig(<span class="hljs-built_in">format</span>=<span class="hljs-string">&quot;%(asctime)s|%(levelname)s|%(filename)s|%(lineno)s|%(message)s&quot;</span>, level=logging.DEBUG)<br>logging.debug(<span class="hljs-string">&quot;This is debug log&quot;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li>asctime: 日志输出时间</li>
<li>levelname: 日志级别</li>
<li>filename: 输出日志的脚本文件</li>
<li>lineno: 输出日志的脚本文件的行数</li>
<li>message: 日志主体内容</li>
</ul>
<h2 id="高级用法"><a href="#高级用法" class="headerlink" title="高级用法"></a>高级用法</h2><p>我们上面知道了，日志可以输出到文件中，也可以根据需要调整日志输出的格式。</p>
<p>但还有个问题，我们输出到文件中之后，就无法再输出到控制台中，这肯定不是我们想要的。</p>
<h3 id="logger"><a href="#logger" class="headerlink" title="logger"></a>logger</h3><p>我们上面使用的时候，大多都是直接使用 <code>logging</code></p>
<p>但是这样的话, 有个问题, 就是这个是通用的logging.</p>
<p>更多的时候, 我们需要使用 <strong>不同</strong> 的logging, 所以我们可以使用 <strong>logger</strong>, 来实例化不同的 logging</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br><br><br>logging.basicConfig(<span class="hljs-built_in">format</span>=<span class="hljs-string">&quot;%(asctime)s|%(levelname)s|%(filename)s|%(lineno)s|%(message)s&quot;</span>, level=logging.DEBUG)<br><br>logger = logging.getLogger(__name__)  <span class="hljs-comment"># 使用时, 必须要传入一个参数来指定logger的名字, 并且每个logger的名字都应该不同</span><br><br>logger.debug(<span class="hljs-string">&quot;test&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>logger几乎包含所有 <code>logging</code> 应该有的功能.</p>
<h3 id="handler"><a href="#handler" class="headerlink" title="handler"></a>handler</h3><p>它们将日志分发到不同的目的地。</p>
<p>可以是文件、标准输出、邮件、或者通过socket、http等协议发送到任何地方</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 输出到控制台的handler</span><br><span class="hljs-comment"># 我们设置了StreamHandler之后，就不需要logging.basicConfig来设置日志级别了</span><br>sh = logging.StreamHandler()<br><br><br><span class="hljs-comment"># 输出到文件的handler</span><br>fh = logging.FileHandler(filename)<br></code></pre></td></tr></table></figure>

<h3 id="Formatter"><a href="#Formatter" class="headerlink" title="Formatter"></a>Formatter</h3><p>通过这个函数，可以给 <strong>handler</strong> 设置 <strong>日志格式</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br>formatter = logging.Formatter(<span class="hljs-string">&quot;%(asctime)s|%(levelname)s|%(filename)s|%(lineno)s|%(message)s&quot;</span>)<br></code></pre></td></tr></table></figure>


<h3 id="logger-handlers-formatter联用"><a href="#logger-handlers-formatter联用" class="headerlink" title="logger/handlers/formatter联用"></a>logger/handlers/formatter联用</h3><p>以上介绍时，只是介绍了怎么定义，那具体怎么串联使用呢？</p>
<p>这里直接给一份写好的脚本定义方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br><br>logger = logging.getLogger(<span class="hljs-string">&quot;test&quot;</span>)<br><br>logger.setLevel(logging.DEBUG)<br><br>sh = logging.StreamHandler()  <span class="hljs-comment"># 定义输出到控制台的handler</span><br>fh = logging.FileHandler(filename=<span class="hljs-string">&quot;./log.log&quot;</span>, encoding=<span class="hljs-string">&quot;utf-8&quot;</span>)  <span class="hljs-comment"># 定义输出到文件的handler</span><br>formatter = logging.Formatter(<span class="hljs-string">&quot;%(asctime)s - %(levelname)s - %(filename)s - %(lineno)s - %(message)s&quot;</span>)  <span class="hljs-comment"># 定义输出格式</span><br><br><span class="hljs-comment"># 分别给两个handler设置格式</span><br>sh.setFormatter(formatter)<br>fh.setFormatter(formatter)<br><br><span class="hljs-comment"># 最后将这两个handler设置到logger身上</span><br>logger.addHandler(sh)<br>logger.addHandler(fh)<br><br><br>logger.debug(<span class="hljs-string">&quot;测试输出&quot;</span>)<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/python/" class="category-chain-item">python</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/python/Python%E5%9F%BA%E7%A1%80/" class="category-chain-item">Python基础</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/Python%E5%9F%BA%E7%A1%80/">#Python基础</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>python常用标准库</div>
      <div>https://walker_kwu.gitee.io/my-blog/2023/03/19/python/base/python常用标准库/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年3月19日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/03/25/python/base/python%E5%B8%B8%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93/" title="python常用第三方库">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">python常用第三方库</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2023/03/18/python/base/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E5%8F%8A%E6%96%87%E4%BB%B6%E5%A4%84%E7%90%86/" title="python异常处理及文件处理">
                        <span class="hidden-mobile">python异常处理及文件处理</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
